/**
 * Created by admin on 2016/10/17.
 */
var assert = require('../assert');

//获取团购的商品列表
exports.getGroupProducts = function (req, res) {
    var responseContent = [];
    var query = new Parse.Query('OPGroupProduct');
    query.include('product');
    query.find().then(function (results) {
        var len = results.length;
        for (var i = 0; i < len; i++) {
            var temp = {};
            var item = results[i];
            temp = assert.obj2dic(item, ['groupPrice', 'personNum']);
            temp['product'] = assert.obj2dic(item.get('product'), ['title', 'salePrice']);
            temp['product']['image'] = item.get('product').get('images')[0];
            responseContent.push(temp);
        }
        res.json({'code': 200, 'message': '获取团购列表成功', 'results': responseContent});
    }, function (error) {
        res.status(400).send(assert.response_sms(400, 'get getGroupBuyProducts error'));
    });
};
//获取单个团购商品详情
exports.getGroupProduct = function (req, res) {
    var groupProductId = req.params.id;
    var isshort = req.query.isshort;
    if (!groupProductId) {
        res.send(assert.response_sms(101, '非法访问'));
        return
    }
    var groupOrderList = [];
    // 建立一个GroupProduct对象
    var GroupProduct = Parse.Object.extend('OPGroupProduct');
    var groupProduct = new GroupProduct();
    groupProduct.id = groupProductId;
    // 查询包含这个GroupProduct的团购
    var queryOrder = new Parse.Query('OPGroupOrder');
    queryOrder.equalTo('groupProduct', groupProduct);
    queryOrder.equalTo('status', 'group');
    queryOrder.descending('lackNum');
    queryOrder.include('user', 'order');
    queryOrder.find().then(function (results) {
        var len = results.length;
        for (var i = 0; i < len; i++) {
            var groupOrder = assert.obj2dic(results[i], ['lackNum']);
            var beginTime = results[i].get('createdAt');
            var endTime = beginTime.setDate(beginTime.getDate() + 1);
            var now = new Date();
            var remainTime = endTime - now.getTime();
            // 如果还没过期才返回
            if (remainTime > 0) {
                groupOrder['endTime'] = remainTime;
                groupOrder['user'] = assert.obj2dic(results[i].get('user'), ['nickname']);
                groupOrder['user']['locality'] = typeof results[i].get('order').get('city') != 'undefined' ? results[i].get('order').get('city') : '火星';
                // 对头像的url进行过滤，对开头是http的进行处理
                var avatar_url = results[i].get('user').get('avatar');
                if (typeof avatar_url == 'undefined'){
                    avatar_url = 'AppIcon512.png'
                }else {
                    var re_http = /http:\/\//;
                    if (re_http.test(avatar_url)) {
                        avatar_url = avatar_url.split('/');
                        avatar_url = avatar_url[avatar_url.length - 1];
                    }
                }
                groupOrder['user']['avatar'] = avatar_url;
                groupOrderList.push(groupOrder);
            } else {
                //过期了要加入到待修改list,再返回后进行处理
                //TODO
            }

        }
        //获取团购商品
        var query = new Parse.Query('OPGroupProduct');
        query.include('product', 'product.type');
        query.get(groupProductId).then(function (result) {
            var temp = {};
            if (isshort) {
                temp['groupProductId'] = result.id;
                temp['isGroup'] = true;
                temp['salePrice'] = result.get('groupPrice');
                temp['title'] = result.get('product').get('title');
                temp['objectId'] = result.get('product').id;
                temp['images'] = result.get('product').get('images')[0];
                res.json({'code': 200, 'message': '获取团购商品成功', 'results': temp});
            } else {
                temp = assert.obj2dic(result, ['groupPrice', 'personNum', 'product']);
                // 把团购的商品的开团信息加入到，团购商品详情中
                if (groupOrderList.length > 2) {
                    temp['groupOrderList'] = groupOrderList;
                } else {
                    temp['groupOrderList'] = groupOrderList.slice(0, 2);
                }
                // 团购商品的country改为包邮
                temp['product'].set('country', '包邮');
                res.json({'code': 200, 'message': '获取团购商品成功', 'results': temp});
            }
        }, function (error) {
            res.send(assert.response_sms(400, 'get getGroupProduct error'));
        });
    }, function (error) {

    });

};
//获取一个团购的的详情
exports.getGroupOrder = function (req, res) {
    var groupOrderId = req.params.id;
    if (assert.check_parms([groupOrderId])) {
        res.send(assert.response_sms(101, 'groupOrderId不能为空'));
        return;
    }
    var userId = req.query.userId;
    var query = new Parse.Query('OPGroupOrder');
    query.include('groupProduct.product', 'user', 'order');
    query.get(groupOrderId).then(function (result) {
        //判断这个团是否过期
        var beginTime = result.get('createdAt');
        var endTime = beginTime.setDate(beginTime.getDate() + 1);
        var now = new Date();
        var remainTime = endTime - now.getTime();
        if ((endTime < now.getTime()) && (result.get('status') == 'group')) {
            //如果过期做一下处理
            result.save({'status': 'fail'}).then(function (ret) {
                // 重新进入这个url
                res.redirect(req.path);
            }, function (error) {
                res.json({'code': 103, 'message': '过期团购,修改状态失败'});
            });
        } else {
            // 没有过期，格式化返回的数据
            var temp = assert.obj2dic(result, ['lackNum', 'status']);
            beginTime = beginTime.setDate(beginTime.getDate()-1);
            temp['createdAt'] = new Date(beginTime).Format('yyyy-MM-dd hh:mm:ss');
            temp['leader'] = assert.obj2dic(result.get('user'), ['nickname']);
            var avatar_url = result.get('user').get('avatar');
            if (typeof avatar_url == 'undefined'){
                avatar_url = 'AppIcon512.png'
            }else {
                var re_http = /http:\/\//;
                if (re_http.test(avatar_url)) {
                    avatar_url = avatar_url.split('/');
                    avatar_url = avatar_url[avatar_url.length - 1];
                }
            }
            temp['leader']['avatar'] = avatar_url;
            temp['groupProduct'] = assert.obj2dic(result.get('groupProduct'), ['groupPrice', 'personNum']);
            temp['groupProduct']['product'] = assert.obj2dic(result.get('groupProduct').get('product'), ['title', 'images', 'price']);
            // 只有是group的情况才计算剩余时间
            if (result.get('status') == 'group') {
                temp['endTime'] = remainTime;
            } else {
                temp['endTime'] = 0;
            }
            // 如果users为空或者undefined直接返回以上数据
            if (typeof result.get('users') == 'undefined') {
                temp['orders'] = [];
                temp['users'] = [];
                res.json({'code': 200, 'message': '获取团购成功', 'results': temp})
            } else if (result.get('users').length > 0) {
                //判断用户是否参加了这个团购
                var userIdList = [];
                result.get('users').map(function (value) {
                    userIdList.push(value.id);
                });
                if (userId == result.get('user').id) {
                    temp['isJoin'] = true;
                } else if (userId in userIdList) {
                    temp['isJoin'] = true;
                } else {
                    temp['isJoin'] = false;
                }
                //返回这个团购已参加用户的order
                var order_list = [];
                result.get('orders').map(function (item) {
                    var query = new Parse.Query('OPOrder');
                    query.select('createdAt', 'user');
                    query.include('user');
                    order_list.push(query.get(item.id));
                });
                temp['orders'] = [];
                // 获取到所有的order之后，拼装数据
                Promise.all(order_list).then(function (results) {
                    results.map(function (item) {
                        var temp_order = {};
                        temp_order['user'] = assert.obj2dic(item.get('user'), ['nickname']);
                        var avatar_url = item.get('user').get('avatar');
                        if (typeof avatar_url == 'undefined'){
                            avatar_url = 'AppIcon512.png'
                        }else {
                            var re_http = /http:\/\//;
                            if (re_http.test(avatar_url)) {
                                avatar_url = avatar_url.split('/');
                                avatar_url = avatar_url[avatar_url.length - 1];
                            }
                        }
                        temp_order['user']['avatar'] = avatar_url;
                        temp_order['createdAt'] = item.get('createdAt').Format('yyyy-MM-dd hh:mm:ss');
                        temp['orders'].push(temp_order);
                    });
                    res.json({'code': 200, 'message': '获取团购成功', 'results': temp})
                }, function (error) {
                    console.log(error.message);
                    res.send(assert.response_sms(401, '查询这个团购的订单出错'));
                });
            } else {
                // 这部分是users为空的状态的返回
                temp['orders'] = [];
                temp['users'] = [];
                res.json({'code': 200, 'message': '获取团购成功', 'results': temp})
            }
        }
    }, function (error) {
        console.log(error.message);
        res.send(assert.response_sms(400, '没有查询到此团购订单'));
    });

};

//获取推荐商品
exports.getRecommendProducts = function (req, res) {
    var query = new Parse.Query('OPGroupProduct');
    query.include('product');
    query.find(function (results) {
        res.send(assert.response_sms(200, '推荐商品', results))
    }, function (error) {

    });
};
//获取首页轮播团购商品
exports.MainPageProducts = function (req, res) {
    var query = new Parse.Query('OPGroupProduct');
    query.include('product');
    query.limit(3);
    query.find(function (results) {
        var responseContent = [];
        results.map(function (result) {
            var temp = {};
            temp['groupProductId'] = result.id;
            temp['isGroup'] = true;
            temp['personNum'] = result.get('personNum');
            temp['groupPrice'] = result.get('groupPrice');
            temp['salePrice'] = result.get('product').get('salePrice');
            temp['title'] = result.get('product').get('title');
            temp['objectId'] = result.get('product').id;
            temp['images'] = result.get('image');
            responseContent.push(temp);
        });
        res.json({'code': 200, 'message': '获取团购商品成功', 'results': responseContent});
    }, function (error) {

    });
};
//开一个团
exports.postGroupOrder = function (req, res, next) {
    if (req.groupOrderId) {
        return next();
    }
    var userId = req.userId;
    var groupProductId = req.groupProductId;
    var orderId = req.orderId;
    // 判断请求参数是否为空
    var isNull = assert.check_parms([userId, groupProductId]);
    if (isNull) {
        res.send(assert.response_sms(101, 'userId,groupProductId不能为空'));
        return;
    }
    // 创建一个order
    var Order = Parse.Object.extend('OPOrder');
    var order = new Order();
    order.id = orderId;
    // 创建一个user
    var user = new Parse.User();
    user.id = userId;
    // 查询出groupProduct
    var GroupOrder = Parse.Object.extend('OPGroupOrder');
    var query = new Parse.Query('OPGroupProduct');
    query.get(groupProductId).then(function (groupProduct) {
        // 创建一个团购
        var groupOrder = new GroupOrder();
        groupOrder.set('lackNum', groupProduct.get('personNum') - 1);
        groupOrder.set('user', user);
        groupOrder.set('order', order);
        groupOrder.set('status', 'group');
        groupOrder.set('orders', []);
        groupOrder.set('users', []);
        groupOrder.set('groupProduct', groupProduct);
        return groupOrder.save();
    }, function (error) {
        // 查询这个团购商品失败
        console.log(error);
    }).then(function (result) {
        // groupOrder保存成功回调
        console.log('开团成功');
        var orderQuery = new Parse.Query('OPOrder');
        orderQuery.get(orderId).then(function (ret) {
            ret.set('groupOrder', result);
            return ret.save();
        }, function (error) {
            // 获取开团user的订单失败
            console.log('获取开团的订单失败', error.message);
        }).then(function (ret) {
            console.log('order 回填 groupOrder成功');
        }, function (error) {
            console.log('order 回填 groupOrder失败', error.message);
        });
    }, function (error) {
        // groupOrder保存失败回调
        console.log(error.message);
        res.send(assert.response_sms(400, '成功创建一个groupOrder失败'));
    });


};
// 参加一个团
exports.joinGroupBuy = function (req, res) {
    var userId = req.userId;
    var groupOrderId = req.groupOrderId;
    var orderId = req.orderId;
    var isNull = assert.check_parms([userId, groupOrderId]);
    if (isNull) {
        res.send(assert.response_sms(101, 'userId,groupProductId不能为空'));
        return;
    }
    var query = new Parse.Query('OPGroupOrder');
    query.get(groupOrderId).then(function (groupOrder) {
        // 创建订单对象
        var Order = Parse.Object.extend('OPOrder');
        var order = new Order();
        order.id = orderId;
        // 创建用户对象
        var user = new Parse.User();
        user.id = userId;
        // 将user和order保存到团购里
        var orders = groupOrder.get('orders');
        orders.push(order);
        var users = groupOrder.get('users');
        users.push(user);
        groupOrder.set('orders', orders);
        groupOrder.set('users', users);
        groupOrder.increment ('lackNum', -1);
        return groupOrder.save();
    }, function (error) {
        console.log('没有查找到对应的groupOrder', error.message);
    }).then(function (ret) {
        // 保存团购信息成功的回调
        console.log('参团成功', ret.id);
        // 判断团购人数是否已经满员
        var lack = ret.get('lackNum');
        if (lack == 0) {
            ret.set('status', 'success');
            return ret.save();
        }
    }, function (error) {
        // 保存团购信息失败的回调
        //TODO 有错误返回错误,直接打印是什么意思
        console.log('参加团购，保存团购信息失败', error.message);
    }).then(function (result) {
        //修改groupOrder状态为success成功的回调
        console.log('参加团购，成功将groupOrder状态修改为success', result.id);
    }, function (error) {
        //修改groupOrder状态为success失败的回调
        console.log('参加团购，将groupOrder状态修改为success失败', error.message);
    });
};

// 检查团购状态
exports.checkGroupStatus = function (req, res) {
    var groupOrderId = req.body.groupOrderId;
    var userId = req.body.userId;
    var user = new Parse.User();
    user.id = userId;
    if (assert.check_parms([groupOrderId])) {
        res.json({'code': 101, 'message': '参数不能为空'})
    }
    var query = new Parse.Query('OPGroupOrder');
    query.select('status', 'user', 'users');
    query.get(groupOrderId).then(function (ret) {
        var responseContent = {};
        var response = true;
        if (ret.get('user').id == userId) {
            response = false;
            responseContent['message'] = '您已开团，不能继续参团';
        }
        if (typeof ret.get('users') == 'undefined') {
            response = true;
        } else if (user in ret.get('users')) {
            responseContent['message'] = '您已参团';
            response = false;
        }
        if (ret.get('status') != 'group') {
            if (ret.get('status') == 'success') {
                responseContent['message'] = '此团已结束';
            } else if (ret.get('status') == 'fail') {
                responseContent['message'] = '此团已过期';
            }
            response = false;
        }
        responseContent['isOk'] = response;
        res.json({'code': 200, 'message': '获取是否可以参团成功', 'results': responseContent});
    }, function (error) {
        res.json({'code': 400, 'message': '未找到这个团购'});
    });
};